package com.fnzx.filter;

import com.fnzx.common.enums.ResponseStatusEnum;
import com.fnzx.common.enums.UserTypeEnum;
import com.fnzx.util.R;
import com.fnzx.util.common.JwtUtil;
import com.fnzx.util.common.ResponseUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Wang Zhifu
 * @create: 2021/10/27 12:19
 * @Description:
 */
@WebFilter(filterName = "tokenFilter",urlPatterns = "/*")
public class TokenFilter implements Filter{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String path = ((HttpServletRequest) request).getRequestURI();
        //需要超级管理员权限的接口
        String[] adminPath={"/iot/article/",
                            "/iot/describeinfo/",
                            "/iot/video/",
                            "/iot/rotationchart/",
                            "/iot/naslink/",
                            "/iot/expert/"};
        for (String s : adminPath) {
            if (path.startsWith(s)){
                //截取方法的路径参数 比如：/iot/article/delete 截取 /delete
                String s1 = path.substring(s.length());
                if (s1.startsWith("info") || s1.startsWith("list")){
                    chain.doFilter(request,response);
                    return;
                }
                String token = ((HttpServletRequest) request).getHeader("token");
                if (JwtUtil.verityToken(token)){
                    Integer userType = Integer.valueOf(JwtUtil.getPayloadInfo(token, "userType"));
                    if (userType.equals(UserTypeEnum.SUPER_ADMIN_TYPE)){
                        chain.doFilter(request,response);
                        return;
                    }
                }else {
                    invalidToken((HttpServletResponse) response);
                    return;
                }
            }
        }
        chain.doFilter(request,response);
    }

    /**
     * token验证失败返回错误信息
     * @param response response对象
     * @throws IOException IO异常
     */
    private void invalidToken(HttpServletResponse response) throws IOException {
        ResponseUtil.writeJson(response, R.error(ResponseStatusEnum.INVALID_TOKEN.getStatus(),ResponseStatusEnum.INVALID_TOKEN.getMsg()));
    }

}
